package com.example.demo.security.service.Impl;

import com.alibaba.fastjson.JSON;
import com.example.demo.security.dao.AdminRoleDao;
import com.example.demo.security.model.AdminGroupRole;
import com.example.demo.security.model.AdminRole;
import com.example.demo.security.model.AdminUser;
import com.example.demo.security.service.AdminGroupRoleService;
import com.example.demo.security.service.AdminUserService;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserDatailsServiceImpl implements UserDetailsService {
    @Autowired
    AdminUserService adminUserService;
    @Autowired
    AdminGroupRoleService adminGroupRoleService;
    @Resource
    AdminRoleDao adminRoleDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户是否存在
        System.out.println(username);
        AdminUser adminUser = adminUserService.adminUserName(username);
        System.out.println(adminUser);

        if (adminUser==null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        //查询权限
        List<AdminGroupRole> adminGroupRoles = adminGroupRoleService.selectAdminGroupRole(adminUser.getGroup_id());
        List<String> adminRoles = adminRoleDao.selectByAdminRole(adminGroupRoles);
        System.out.println(adminGroupRoles);
        System.out.println(adminRoles);
        String str = StringUtils.join(adminRoles,',');
        System.out.println(str);

        System.out.println(adminRoles);
        return new User(username,adminUser.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList(str));
    }
}
